package com.leboncoin.mail;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import java.util.logging.Logger;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;

import com.leboncoin.bean.ClassifiedBean;
import com.leboncoin.bean.SearchItemBean;
import com.leboncoin.bean.SubscriptionBean;
import com.leboncoin.http.HttpManager;

public class MailManager {

	static Logger logger = Logger.getLogger(MailManager.class.getName());	
	public MailManager() {
		// TODO Auto-generated constructor stub
	}

	public static void sendMail(SubscriptionBean subscriptionBean) {

		// Create the email message
		HtmlEmail email = new HtmlEmail();

		try {
			setCommonsPart(email, subscriptionBean);

		} catch (Exception e) {
			logger.severe("Cannot set email commons part: "+e);
			logger.severe(e.getMessage());
			logger.severe(e.getCause().getMessage());
		}
		
		populateHtmlMimeMail(email, subscriptionBean);

		try {
			// send the email
			email.send();
				
		} catch (Exception e) {
			logger.severe("Cannot send email: "+e);
			logger.severe(e.getMessage());
			logger.severe(e.getCause().getMessage());
		}
	}
	
	protected static void populateHtmlMimeMail(HtmlEmail email, SubscriptionBean subscriptionBean){
	
		// Create email body
		String textBody = "<html>";
		for (SearchItemBean searchItemBean:subscriptionBean.getSearchItems()){
			if (searchItemBean.getSearchResults().size() > 0){
				textBody += "<b>RESULTATS ";
				if (searchItemBean.getSearchText() != null){
					textBody += "POUR "+searchItemBean.getSearchText();
				}
				if (searchItemBean.getSearchCategory() != null){
					textBody += " DANS "+searchItemBean.getSearchCategory();
				}
				textBody += "</b>";
				if (searchItemBean.getPriceMax() != null || searchItemBean.getPriceMin() != null){
					textBody += " <br />";
					if (searchItemBean.getPriceMin() != null){				
						textBody += " Prix min:"+searchItemBean.getPriceMin();
					}
					if (searchItemBean.getPriceMax() != null){				
						textBody += " Prix max:"+searchItemBean.getPriceMax();
					}
				}
				if (searchItemBean.getSearchLocation() != null){
					textBody += " <br />";
					textBody += " Lieu:"+searchItemBean.getSearchLocation().toString();
					
					if (searchItemBean.getZipCodes() != null && searchItemBean.getZipCodes().size()>0){				
						textBody += " Codes postaux:";
						for(String zipCode:searchItemBean.getZipCodes()){
							textBody += " "+zipCode;
						}
					}
				}
				textBody += "<br /><table border=\"0\">";
				for (ClassifiedBean classifiedBean:searchItemBean.getSearchResults()){
					textBody += "<tr><td><a href=\""+classifiedBean.getLink()+"\">";
					textBody += classifiedBean.getTitle();
					textBody += "</a></td><td>";
					if (classifiedBean.getPrice() != null){
						textBody += Math.round(classifiedBean.getPrice())+"&euro;";
					}
					textBody += "</td><td><table border=\"0\"><tr>";			
					for (String imageLink:classifiedBean.getImageLinks()){
						textBody += "<td>";
						textBody += "<img src=\"" + imageLink + "\" height=\"136\" \">";
						textBody += "</td>";
					}
					textBody += "</tr></table></td></tr>";
				}
				textBody += "</table><br />";
			}
		}
		textBody += "</html>";

		email.setContent(textBody, "text/html");
		
	}
	protected static void populateHtmlMail(HtmlEmail email, List<ClassifiedBean> classifieds) {

		try {

			// Create the email body
			String textBody = "<html><table border=\"0\">";
			int imgIndex = 0;
			for (ClassifiedBean classifiedBean:classifieds){
				textBody += "<tr><td><a href=\""+classifiedBean.getLink()+"\">";
				textBody += classifiedBean.getTitle();
				textBody += "</a></td><td>";
				textBody += classifiedBean.getPrice();
				textBody += "</td><td><table border=\"0\"><tr>";			
				for (String imageLink:classifiedBean.getImageLinks()){
					textBody += "<td>";
					URL url = new URL(imageLink);
					String cid = email.embed(url, classifiedBean.getTitle()+"-"+imgIndex++);
					textBody += "<img src=\"cid:" + cid	+ "\" height=\"100px\" \">";
					textBody += "</td>";
				}
				textBody += "</tr></table></td></tr>";
			}
			textBody += "</table></html>";

			// set the html message
			email.setHtmlMsg(textBody);

			// set the alternative message
			//email.setTextMsg("Your email client does not support HTML messages");

			// send the email
			email.send();
		} catch (Exception e) {
			logger.severe(e.getMessage());
		}
	}
	
	protected static void populateMultipartMail(MultiPartEmail email, List<ClassifiedBean> classifieds) 
			throws MessagingException, MalformedURLException, EmailException, IOException, URISyntaxException{
		
	    MimeMultipart multipart = new MimeMultipart();

	    HttpManager.downloadClassifiedImages(classifieds);
	    
		for (ClassifiedBean classifiedBean:classifieds){
		    MimeBodyPart messageBodyPart = new MimeBodyPart();
			
			String textBody = "<table border=\"0\">";
			textBody += "<tr><td><a href=\""+classifiedBean.getLink()+"\">";
			textBody += classifiedBean.getTitle();
			textBody += "</a></td><td>";
			textBody += classifiedBean.getPrice();
			textBody += "</td><td><table border=\"0\"><tr>";			
			for (java.io.File imageFile:classifiedBean.getImageFiles()){
				String fileName = imageFile.getName();
				textBody += "<td>";
				textBody += "<img src=\"" + fileName + "\" height=\"50px\" width=\"50px\" \">";
				textBody += "</td>";
			    DataSource source = new FileDataSource(imageFile);
			    messageBodyPart.setDataHandler(new DataHandler(source));
			    messageBodyPart.setFileName(fileName);
			    messageBodyPart.setDisposition(MimeBodyPart.INLINE);
			    //messageBodyPart.setDataHandler(dh)
			}
			textBody += "</tr></table></td></tr>";
			textBody += "</table>";
		    
		    messageBodyPart.setContent(textBody, "text/html");
			multipart.addBodyPart(messageBodyPart);
		}

	    email.setContent(multipart);

	}
	
	protected static void setCommonsPart(Email email, SubscriptionBean subscriptionBean) throws EmailException{
		email.setHostName("smtp.gmail.com");
		email.setSSL(true);
		email.setSmtpPort(465);
		email.setSslSmtpPort("465");
		for(String emailAdress:subscriptionBean.getEmailAdresses()){
			email.addTo(emailAdress);
		}
		email.setFrom("bcaure@gmail.com", "Robot Leboncoin");
		email.setAuthentication("bcaure@gmail.com", "3u5e6ndelphineve");
		int resultNumber = 0;
		for (SearchItemBean searchItemBean:subscriptionBean.getSearchItems()){
			resultNumber+=searchItemBean.getSearchResults().size();
		}
		email.setSubject(resultNumber+" annonces pour '"+subscriptionBean.getName()+"'");		
	}

}
